package org.liurb.springboot.starter.common.validator;

import cn.hutool.core.date.LocalDateTimeUtil;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.liurb.springboot.starter.common.annotation.DateTimeAnnotation;


/**
 * 时间格式校验
 *
 * 使用时将注解加在dto的字段中
 *
 * @Author Liurb
 * @Date 2022/11/28
 */
public class DateTimeValidator implements ConstraintValidator<DateTimeAnnotation, String> {

    private DateTimeAnnotation dateTime;

    @Override
    public void initialize(DateTimeAnnotation dateTime) {
        this.dateTime = dateTime;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {

        if (value == null) {
            return true;
        }

        String format = dateTime.format();

        if (value.length() != format.length()) {
            return false;
        }

        try {

            LocalDateTimeUtil.parseDate(value, format);

        } catch (Exception e) {
            return false;
        }

        return true;
    }

}
